<?php
define("THIS_PAGE", "users");

require_once($_SERVER["DOCUMENT_ROOT"] . "/../sys/libs/init.lib");
include($_SERVER["DOCUMENT_ROOT"] . "/../sys/includes/adminheader.php");

print "<div class=\"pagebody\">";


if (isset($_REQUEST["do"]) && !empty($_REQUEST["do"]) && strtolower($_REQUEST["do"]) == "save") {

	$errors = array();

	if ($_REQUEST["frm_password1"] !== $_REQUEST["frm_password2"]) {
		$errors[] = "The passwords entered do not match!";
	}

	if (empty($_REQUEST["frm_usertypeid"])) {
		$errors[] = "The user needs a user type";
	}

	if (empty($_REQUEST["frm_username"])) {
		$errors[] = "The user needs a username!";
	}

	if (empty($_REQUEST["frm_password1"]) || empty($_REQUEST["frm_password2"])) {
		$errors[] = "The user needs a password!";
	}

	$savefields = array(
		"frm_usertypeid" 	=> "UserTypeID",
		"frm_username"		=> "UserName",
		"frm_firstname"		=> "FirstName",
		"frm_surname"		=> "Surname",
		"frm_password"		=> "Password",
		"frm_email"			=> "Email"
	);

	$savedata = array();

	if (empty($errors)) {

		$_REQUEST["frm_password"] = $_REQUEST["frm_password1"];

		unset($_REQUEST["frm_password1"]);
		unset($_REQUEST["frm_password2"]);

		foreach ($_REQUEST as $key => $val) {
			if (strtolower(substr($key, 0, 4)) == "frm_") {
				$savedata[$savefields[$key]] = $val;
			}
		}

		if ($uid = $db->insert("users", $savedata)) {
			print "Saved Successfully";
			$_REQUEST["userid"] = $uid;
		}

	}
}

if (!empty($errors)) {
	var_dump($errors);
}

if (!empty($_REQUEST["userid"])) {
	$user = $db->get("SELECT * FROM users WHERE id = " . $_REQUEST["userid"]);
}

$usertype_options = $db->getarray("SELECT * FROM usertype");

?>
	<h1>User Administration</h1>
	<table width="100%">
	<form method="post" action="<?php $_SERVER["PHP_SELF"]; ?>">
	<tr>
		<td>User Type:</td>
		<td><select name="frm_usertypeid" id="frm_usertypeid">
			<option value="">Choose</option>
			<?php
			foreach($usertype_options as $key => $option) {
				$selected = "";
				if (isset($user) && !empty($user)) {
					$selected = ($option->id == $user->UserTypeID ? "selected=\"selected\"" : "");
				}
				print "<option value=\"{$option->id}\" {$selected}>{$option->Title}</option>";
			}
			?>
		</select></td>
	</tr>
	<tr>
		<td>First Name</td>
		<td><input type="text" name="frm_firstname" id="frm_firstname" /></td>
	</tr>
	<tr>
		<td>Surname:</td>
		<td><input type="text" name="frm_surname" id="frm_surname" /></td>
	</tr>
	<tr>
		<td>Username:</td>
		<td><input type="text" name="frm_username" id="frm_username" /></td>
	</tr>
	<tr>
		<td>Password:</td>
		<td><input type="password" name="frm_password1" id="frm_password1" /></td>
	</tr>
	<tr>
		<td>Password (confirm):</td>
		<td><input type="password" name="frm_password2" id="frm_password2" /></td>
	</tr>
	<tr>
		<td>Email:</td>
		<td><input type="text" name="frm_email" id="frm_email" /></td>
	</tr>
	<tr>
		<td></td>
		<td><input type="submit" name="do" id="do" value="save" /></td>
	</table>

<?php
?>